<template>
  <div class="user-container">
    <el-card>
      <!--  -->
      <el-form ref="search" :inline="true" class="user-form">
        <el-form-item>
          <el-input
            v-model="username"
            prpo="name"
            placeholder="根据用户名搜索"
            size="small"
          />
        </el-form-item>
        <el-form-item>
          <el-button size="small" @click="clearFn">清空</el-button>
          <el-button type="primary" size="small" @click="searchFn">
            搜索
          </el-button>
        </el-form-item>
        <el-form-item class="adduser">
          <el-button
            size="small"
            type="success"
            @click="openDialog('新增用户')"
          >
            <i class="el-icon-edit" />
            新增用户
          </el-button>
        </el-form-item>
      </el-form>
      <div class="tips">
        <i class="el-icon-info" />
        <span>共 {{ total }} 条记录</span>
      </div>
      <el-table v-loading="loading" :data="userList">
        <el-table-column
          label="序号"
          prop="index"
          :index="indexFn"
          type="index"
        />
        <el-table-column label="邮箱" prop="email" />
        <el-table-column label="联系电话" prop="phone" />
        <el-table-column label="用户名" prop="username" />
        <el-table-column label="权限组名称" prop="permission_group_title" />
        <el-table-column label="角色" prop="role" />
        <el-table-column label="操作" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              plain
              icon="el-icon-edit"
              circle
              @click="openDialog('编辑用户', row.id)"
            />
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              circle
              @click="remove(row.id)"
            />
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        :current-page="page"
        :page-sizes="[5, 10, 15, 20, 25]"
        :page-size="pagesize"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="currentChange"
      />
    </el-card>
    <el-dialog :visible.sync="visibleDialog" @close="close">
      <h3 slot="title" class="dialog-title">{{ title }}</h3>
      <el-form
        ref="addform"
        label-width="200px"
        :model="addform"
        :rules="rules"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addform.username" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addform.email" />
        </el-form-item>
        <el-form-item v-if="title === '新增用户'" label="密码" prop="password">
          <el-input v-model="addform.password" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-input v-model="addform.role" />
        </el-form-item>
        <el-form-item label="权限组名称" prop="permission_group_id">
          <el-select v-model="addform.permission_group_id">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="addform.phone" />
        </el-form-item>
        <el-form-item label="介绍" prop="introduction">
          <el-input
            v-model="addform.introduction"
            type="textarea"
            style="width: 280px"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" style="text-align: center">
        <el-button @click="visibleDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmAdd">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getUserListApi,
  getPermissionsApi,
  getUserDetailApi,
  delUserApi,
  editUserApi,
  addUserApi
} from '@/api/user'
export default {
  data() {
    return {
      username: '',
      number: 4,
      loading: false,
      userList: [], // 用户列表数据
      page: 1, // 页数
      pagesize: 10, // 每页多少数据
      total: 0, // 数据总数
      visibleDialog: false,
      addform: {
        avatar: '',
        username: '',
        email: '',
        password: '',
        role: '',
        permission_group_id: '',
        phone: '',
        introduction: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        email: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        password: [{ required: true, message: '请输入用户名', trigger: 'blur' }]
      },
      title: '',
      id: '',
      roleList: [],
      permission_group_title: 0
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    // 清空搜索框
    clearFn() {
      this.username = ''
      this.getUserList()
    },
    // 搜索用户
    searchFn() {
      this.keyword = this.username
      this.getUserList()
    },
    // 获取用户列表
    async getUserList() {
      const { list, counts } = await getUserListApi(
        this.page,
        this.pagesize,
        this.username
      )
      // console.log(list)
      this.userList = list
      // console.log(this.userList)
      this.total = counts
    },
    handleSizeChange(val) {
      // 更新每页条数
      this.pagesize = val
      // 更新每条条数，页码重置为第一页
      this.page = 1
      // 重新获取新的页码的数据
      this.getUserList()
    },
    // currentPage改变时触发
    // 目标：页码切换渲染新一页数据
    currentChange(val) {
      // 更新当前页
      console.log(val)
      this.page = val
      // 重新获取新的页码的数据
      this.getUserList()
    },
    // 切换页码更新序号
    indexFn(index) {
      // 当前返回的序号 前面有多少条数据
      // 前面一共有多少条数据 = 前面的页数 * 每页条数
      return index + 1 + (this.page - 1) * this.pagesize
    },
    async openDialog(title, id) {
      // console.log(id)
      this.title = title
      this.visibleDialog = true
      this.id = id
      const data = await getPermissionsApi()
      this.roleList = data
      // console.log(this.roleList)
      if (title === '编辑用户') {
        const data = await getUserDetailApi(id)
        // console.log(data)
        this.addform.username = data.username
        this.addform.email = data.email
        this.addform.role = data.role
        this.roleList.forEach((item) => {
          if (item.id === data.permission_group_id) {
            this.permission_group_title = item.title
          }
        })
        this.addform.permission_group_id = this.permission_group_title
        this.addform.phone = data.phone
        this.addform.introduction = data.introduction
      }
    },
    remove(id) {
      this.$confirm('此操作将永久删除此用户，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await delUserApi({ id })
          this.$message.success('删除用户成功')
          this.getUserList()
        })
        .catch(() => {
          // 点击取消触发的方法
          this.$message.info('已取消删除')
        })
    },
    close() {
      this.$refs.addform.resetFields()
    },
    confirmAdd() {
      this.roleList.forEach((item) => {
        if (item.title === this.addform.permission_group_id) {
          this.addform.permission_group_id = item.id
        }
      })

      this.$refs.addform.validate(async (valid) => {
        if (valid) {
          const data = {
            ...this.addform,
            permission_group_id: this.addform.permission_group_id
          }
          // console.log(data)
          if (this.title === '新增用户') {
            await addUserApi(data)
            this.$message.success('添加用户成功')
          } else {
            await editUserApi(this.id, data)
            this.$message.success('修改用户成功')
          }
          this.visibleDialog = false
          this.getUserList()
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.user-container {
  padding: 20px;
  .user-form {
    position: relative;
    .adduser {
      position: absolute;
      right: 0;
    }
  }
  .tips {
    padding: 10px 15px;
    margin-bottom: 10px;
    font-size: 14px;
    background: #ececec;
    color: #999;
    .el-icon-info {
      margin-right: 10px;
      color: #666;
    }
  }
}
::v-deep .el-input__inner {
  height: 32px;
}
.el-table {
  ::v-deep th {
    background-color: #fafafa !important;
  }
}
::v-deep .el-dialog__header {
  background-color: #409eff;
  padding: 20px;
}

.dialog-title {
  padding: 0;
  margin: 0;
  color: #fff;
  font-weight: normal;
  font-size: 18px;
  height: 18px;
  line-height: 18px;
}
.el-form {
  ::v-deep input {
    width: 280px !important;
  }
}
</style>
>
